//
// Created by hkkzzxz on 24-9-3.
//

#include "UserController.h"
#include "UserService.h"
#include "JWT.h"

void UserController::login(std::string &data, http::request<http::dynamic_body> &httpRequest,
                           http::response<http::dynamic_body> &httpResponse) {
    Json::Value root;
    Json::Value srcRoot;

    //尝试解析字符串
    if (parseRequestBody(httpRequest, srcRoot)) {
        auto id = srcRoot["id"].asString();
        auto password = srcRoot["password"].asString();

        std::unique_ptr<IUserService> userService = std::make_unique<UserService>();
        std::string result = userService->login(id, password);

        if (!result.empty()) {
            httpResponse.result(http::status::ok);
            root["code"] = 0;
            //生成token
            auto jwt = std::make_unique<JWT>();
            Json::Value payload;
            payload["id"] = id;
            payload["identity"] = result;
            root["token"] = jwt->create(payload);
            root["identity"] = result;
            root["message"] = "Successful login";
        } else {
            httpResponse.result(http::status::bad_request);
            root["code"] = 1002;
            root["token"] = "";
            root["identity"] = "";
            root["message"] = "Failed login";
        }
    } else {
        httpResponse.result(http::status::bad_request);
        root["code"] = 1001;
        root["token"] = "";
        root["identity"] = "";
        root["message"] = "Failed to parse JSON data!";
    }

    setHttpResponse(httpResponse, root);
}
